import { App, Form } from "antd";
import { useDialog } from "./useDialog";

export const useFormDialog = (props) => {

    const dialog = useDialog(props);
    const form = useForm(props);

    return {
        ...dialog,
        ...form,
    };
};

/**
 * props = {
 *   save: api,
 *   edit: api,
 *   col: 列数,
 *   items: 表单项,
 * }
 */
export const useForm = (props = {}) => {
    const { message } = App.useApp();
    // 列数
    const col = props.col || 1;
    // 表单项
    const items = props.items || [];

    /**
     * 提交表单
     * @param {*} model 表单数据
     * @param {*} callback 回调函数  此回调函数中不该有参数
     */
    function onSubmit(model, callback = undefined) {
        if (!model) {
            message.error('表单为空！');
            return;
        }
        if (model.id) {
            if (!props.edit) {
                message.error('未定义编辑接口！');
                throw new Error('未定义编辑接口');
            }

            props.edit(model).then(resp => {
                if (resp?.data) {
                    message.success('保存成功！');
                    typeof callback === 'function' && callback();
                }
            })
        } else {
            if (!props.save) {
                message.error('未定义保存接口！');
                throw new Error('未定义编辑接口');
            }
            props.save(model).then(resp => {
                if (resp?.data) {
                    message.success('保存成功！');
                    typeof callback === 'function' && callback();
                }
            });
        }
    }

    return {
        col,
        items,
        onSubmit,
    }
};